from django.shortcuts import render
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from cartapp.views import check
from orderapp.sers import *


class AddressView(APIView):
    @method_decorator(check)
    def post(self,request):
        request.data['user']=request.uid
        ser=AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg':'添加成功'})
        print(ser.errors)
        return  Response({'msg':'添加失败','errors':ser.errors})
    @method_decorator(check)
    def get(self,request):
        uid=request.uid
        queryset=Address.objects.filter(user_id=uid)
        ser=AddressSer(queryset,many=True)
        return Response({'msg':'查询成功','code':200,'data':ser.data})

    @method_decorator(check)
    def put(self,request):
        uid=request.uid
        aid=request.data.get('id')        # 要修改哪个地址的id
        Address.objects.filter(id=aid).update(flag=1)    # 修改为1
        # 其他地址设置为0
        Address.objects.filter(user_id=uid).exclude(id=aid).update(flag=0)
        return Response({'msg':'修改成功'})




